package org.syncsoft.overalt.gui.impl.componentPlugin;

import java.util.HashMap;
import java.util.Map;

import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

import org.syncsoft.overalt.gui.api.WindowContextValue;
import org.syncsoft.overalt.gui.api.componentPlugin.IComponentPlugin;

/**
 * 
 * @author tptfc
 *
 */
public class TextComponentPlugin implements IComponentPlugin {
	private Map<String, JTextComponent> textComponents;
	
	{
		setTextComponents(new HashMap<String, JTextComponent>());
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.gui.swing.api.IComponentPlugin#getContext()
	 */
	@Override
	public WindowContextValue getContext() {
		WindowContextValue context = new WindowContextValue();
		buildContext(context);
		return context;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.gui.swing.api.IComponentPlugin#buildContext(org.syncsoft.overalt.gui.swing.api.ContextWindowValue)
	 */
	@Override
	public void buildContext(WindowContextValue context) {
		if (context != null) {
			for (String key : getTextComponents().keySet()) {
				context.addValue(key, getTextComponentValue(key));
			}
		}
	}
	
	/**
	 * new text field
	 * 
	 * @precondition	key not is null
	 * @postcondition	getTextComponent(key) not is null
	 * 					return null if key is null
	 * 
	 * @param key
	 * @return
	 */
	public JTextField newTextField(String key) {
		JTextField textField = null;
		
		if (key != null) {
			textField = new JTextField();
			getTextComponents().put(key, textField);
		}
		
		return textField;
	}
	
	/**
	 * new text area
	 * 
	 * @precondition	key not is null
	 * @postcondition	getTextComponent(key) not is null
	 * 					return null if key is null
	 * 
	 * @param key
	 * @return
	 */
	public JTextArea newTextArea(String key) {
		JTextArea textArea = null;
		
		if (key != null) {
			textArea = new JTextArea();
			getTextComponents().put(key, textArea);
		}
		
		return textArea;
	}
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public JPasswordField newPasswordField(String key) {
		JPasswordField passwordField = new JPasswordField();
		getTextComponents().put(key, passwordField);
		return passwordField;
	}
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public JTextComponent getTextComponent(String key) {
		return getTextComponents().get(key);
	}
	
	/**
	 * @postcondition return null if doesn't exist a value to this key
	 * @param key
	 * @return 
	 */
	protected String getTextComponentValue(String key) {
		String value = null;
		
		JTextComponent component = getTextComponents().get(key);
		
		if (component != null) {
			value = component.getText();
		}
		
		return value;
	}

	private Map<String, JTextComponent> getTextComponents() {
		return textComponents;
	}

	private void setTextComponents(Map<String, JTextComponent> textComponents) {
		this.textComponents = textComponents;
	}

}
